package com.aluka.nirvana.framework.core.context;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Http请求上下文管理工具
 * @author gongli
 * @since 2019/12/25
 */
public class ServletContextAware {

	/**
	 * @return 获取request
	 */
	public static HttpServletRequest getRequest() {
		ServletRequestAttributes requestAttributes = getRequestAttributes();
		return requestAttributes == null ? null : requestAttributes.getRequest();
	}


	/**
	 * @return 获取response
	 */
	public static HttpServletResponse getResponse() {
		ServletRequestAttributes requestAttributes = getRequestAttributes();
		return requestAttributes == null ? null : requestAttributes.getResponse();
	}

	/**
	 * @return 获取session
	 */
	public static HttpSession getSession() {
		HttpServletRequest request = getRequest();
		return request == null ? null : request.getSession();
	}

	/**
	 * @param headerName 请求头名称
	 * @return 获取Header
	 */
	public static String getHeader(String headerName) {
		HttpServletRequest request = getRequest();
		return request == null ? null : request.getHeader(headerName);
	}

	/**
	 * @return 获取ServletRequestAttributes
	 */
	public static ServletRequestAttributes getRequestAttributes() {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return attributes == null ? null : (ServletRequestAttributes) attributes;
	}

	/**
	 * 将字符串渲染到客户端
	 * 
	 * @param response
	 *            渲染对象
	 * @param string
	 *            待渲染的字符串
	 * @return null
	 */
	public static String renderString(HttpServletResponse response, String string) {
		try {
			response.setContentType("application/json");
			response.setCharacterEncoding("utf-8");
			response.getWriter().print(string);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 渲染下载文件名称
	 * @param fileName 文件名
	 * @return 文件名称
	 */
	public static String renderFileDownloadFileName(String fileName)
			throws UnsupportedEncodingException {
		final String agent = getRequest().getHeader("USER-AGENT");
		String filename = fileName;
		if (agent.contains("MSIE")) {
			// IE浏览器
			filename = URLEncoder.encode(filename, "utf-8");
			filename = filename.replace("+", " ");
		} else if (agent.contains("Firefox")) {
			// 火狐浏览器
			filename = new String(fileName.getBytes(), "ISO8859-1");
		} else if (agent.contains("Chrome")) {
			// google浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		} else {
			// 其它浏览器
			filename = URLEncoder.encode(filename, "utf-8");
		}
		return filename;
	}


}